const OrderModel = require('../models/orderModel');
const CartModel = require('../models/cartModel');
const { success, error, notFound } = require('../utils/response');

const OrderController = {
  // 创建订单
  createOrder: async (req, res) => {
    try {
      const userId = req.user.id;
      const { address, phone, note, items } = req.body;
      
      if (!address || !phone) {
        return error(res, '收货地址和联系电话为必填项', 400);
      }
      
      // 验证购物车中的商品
      const cartItems = await CartModel.getCartByUserId(userId);
      const cartItemIds = cartItems.map(item => item.id);
      
      // 检查请求的商品是否在购物车中
      const validItems = items.filter(item => 
        cartItemIds.includes(item.cart_item_id) && 
        item.quantity > 0
      );
      
      if (validItems.length === 0) {
        return error(res, '购物车中没有有效商品', 400);
      }
      
      // 计算总金额
      const totalAmount = validItems.reduce((sum, item) => {
        const cartItem = cartItems.find(ci => ci.id === item.cart_item_id);
        return sum + (cartItem.price * item.quantity);
      }, 0);
      
      // 创建订单
      const orderId = await OrderModel.createOrder({
        user_id: userId,
        total_amount: totalAmount,
        address,
        phone,
        note,
        items: validItems.map(item => ({
          product_id: item.product_id,
          quantity: item.quantity,
          price: item.price
        }))
      });
      
      // 清空购物车
      await CartModel.clearCart(userId);
      
      success(res, { orderId }, '订单创建成功', 201);
    } catch (err) {
      console.error(err);
      error(res, '创建订单失败', 500);
    }
  },
  
  // 获取用户订单列表
  getOrders: async (req, res) => {
    try {
      const userId = req.user.id;
      const { status, limit = 10 } = req.query;
      const orders = await OrderModel.getOrdersByUserId(userId, {
        status,
        limit: parseInt(limit)
      });
      success(res, orders);
    } catch (err) {
      console.error(err);
      error(res, '获取订单列表失败', 500);
    }
  },
  
  // 获取订单详情
  getOrderById: async (req, res) => {
    try {
      const userId = req.user.id;
      const order = await OrderModel.getOrderById(req.params.id);
      
      if (!order || order.user_id !== userId) {
        return notFound(res, '订单不存在');
      }
      
      success(res, order);
    } catch (err) {
      console.error(err);
      error(res, '获取订单详情失败', 500);
    }
  },
  
  // 更新订单状态 (需要管理员权限)
  updateOrderStatus: async (req, res) => {
    try {
      // 这里应该添加权限检查中间件
      const { status } = req.body;
      
      if (!status) {
        return error(res, '订单状态为必填项', 400);
      }
      
      const successUpdate = await OrderModel.updateOrderStatus(req.params.id, status);
      
      if (!successUpdate) {
        return notFound(res, '订单不存在或更新失败');
      }
      
      success(res, null, '订单状态更新成功');
    } catch (err) {
      console.error(err);
      error(res, '更新订单状态失败', 500);
    }
  },
  
  // 取消订单
  cancelOrder: async (req, res) => {
    try {
      const userId = req.user.id;
      const order = await OrderModel.getOrderById(req.params.id);
      
      if (!order || order.user_id !== userId) {
        return notFound(res, '订单不存在');
      }
      
      if (order.status !== 'pending' && order.status !== 'processing') {
        return error(res, '只有待处理或处理中的订单可以取消', 400);
      }
      
      const successCancel = await OrderModel.cancelOrder(req.params.id);
      
      if (!successCancel) {
        return error(res, '取消订单失败', 500);
      }
      
      success(res, null, '订单已取消');
    } catch (err) {
      console.error(err);
      error(res, '取消订单失败', 500);
    }
  }
};

module.exports = OrderController;